<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="门票名称" prop="venuesName">
        <el-input
          v-model="queryParams.venuesName"
          placeholder="请输入门票名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
            <el-form-item label="开始时间" prop="stockDateStart">
        <el-date-picker clearable
          v-model="queryParams.stockDateStart"
          type="date"
          :picker-options="startPickerOptionsQuery"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="stockDateEnd">
        <el-date-picker clearable
          v-model="queryParams.stockDateEnd"
          type="date"
          :picker-options="endPickerOptionsQuery"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-hasPermi="['ticket:venuesbusiness:query']">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ticket:venuesbusiness:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ticket:venuesbusiness:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ticket:venues:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="venuesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="门票名称" align="center" prop="venuesName" />
      <el-table-column label="联系电话" align="center" prop="venuesPhone" />
      <!-- <el-table-column label="类别(取字典表)" align="center" prop="venuesType" /> -->
      <el-table-column label="限购数量" align="center" prop="limitPurchaseNum" />
      <!-- <el-table-column label="状态" align="center" prop="venuesStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ticket_venues_status" :value="scope.row.venuesStatus"/>
        </template>
      </el-table-column> -->
      <el-table-column label="场馆名称" align="center" prop="name" />
      <el-table-column label="日期" align="center" prop="venuesDate" />
      <el-table-column label="方案名称" align="center" prop="programmeName" />

      <el-table-column label="认证方式" align="center" prop="scenicAuth">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_auth" :value="scope.row.scenicAuth"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ticket:venuesbusiness:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场馆门票对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal="dialogIsCloseOnModal" :close-on-press-escape="dialogIsCloseOnModal">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <!-- 景区信息 -->
        <el-divider content-position="left">场馆信息</el-divider>
        <el-row>
          <el-col :span="24">
            <el-col :span="11">
              <el-form-item label="场馆">
                  <el-select
                    v-model="form.ticOtherBaseId"
                    placeholder="请选择场馆"
                    clearable
                    style="width: 240px"
                    @change='changeScenicSelect'
                    disabled
                  >
                    <el-option
                      v-for="dict in dictScenicList"
                      :key="dict.ticOtherId"
                      :label="dict.name"
                      :value="dict.ticOtherId"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- 选择场馆后展示详细信息 -->
          <el-col :span="24" v-if='form.ticOtherBaseId'>
            <el-col :span="11">
              <el-form-item label="星级" prop="starDetail">
                <el-input v-model="dictScenicListSelected.starDetail" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开放时间" >
                <el-input v-if="dictScenicListSelected.openTimeStart" :value="`${dictScenicListSelected.openTimeStart}-${dictScenicListSelected.openTimeEnd}`" disabled/>
                <el-input v-else value="" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item label="场馆信息">
                <editor v-model="dictScenicListSelected.introduceDetails" :readOnly='false' :min-height="100"/>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item label="游客须知">
                <editor v-model="dictScenicListSelected.touristNotice" :readOnly='false' :min-height="100"/>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="地理位置" >
                <el-input v-model="dictScenicListSelected.addressDetails" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="坐标点" prop="starDetail">
                <el-input v-if="dictScenicListSelected.latitude &&dictScenicListSelected.longitude" :value="`${dictScenicListSelected.latitude}-${dictScenicListSelected.longitude}`" disabled/>
                <el-input v-else value="" disabled/>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>

        <!-- 门票信息 -->
        <el-divider content-position="left">门票信息</el-divider>
        <el-row>
          <el-col :span="11">
              <el-form-item label="门票" prop="venuesId">
                  <el-select
                    v-model="form.venuesId"
                    placeholder="请选择门票"
                    clearable
                    style="width: 240px"
                    @change='changeStockSelect'
                    :disabled='isEdit'
                  >
                    <el-option
                      v-for="dict in dictStockList"
                      :key="dict.venuesId"
                      :label="dict.venuesName"
                      :value="dict.venuesId"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
          <el-col :span="24" v-if='form.venuesId'>
          <el-col :span="11">
            <el-form-item label="联系电话" prop="venuesPhone">
              <el-input v-model="dictStockListSelected.venuesPhone" placeholder="请输入联系电话" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="限购数量" prop="limitPurchaseNum">
              <el-input-number v-model="dictStockListSelected.limitPurchaseNum" disabled placeholder="请输入限购数量" :min="0"  controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="认证方式" prop="scenicAuth" >
              <el-select
                  v-model="dictStockListSelected.scenicAuth"
                  placeholder="认证方式"
                  clearable
                  disabled
                >
                  <el-option
                    v-for="dict in dict.type.sys_user_auth"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!isEdit">
              <el-form-item label="批量添加时间" prop='endTime'>
              <el-date-picker
                v-model="form.startTime"
                :picker-options="startPickerOptions"
                type="datetime"
                :editable="false"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择开始时间"
                />
                <span> - </span>
            <el-date-picker
                v-model="form.endTime"
                :picker-options="endPickerOptions"
                type="datetime"
                :editable="false"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结束时间"
                />
              </el-form-item>
          </el-col>
          <el-col :span="11" v-else>
             <el-form-item label="批量添加时间">
                <el-input type="text" :value="scenicStockDate" disabled/>
              </el-form-item>
          </el-col>
          </el-col>
        </el-row>

        <el-divider content-position="left">方案信息</el-divider>
          <el-row>
            <el-col :span="24">
            <el-col :span="11">
              <el-form-item label="方案" prop="venuesProgrammeId">
                  <el-select
                    v-model="form.venuesProgrammeId"
                    placeholder="请选择方案"
                    clearable
                    style="width: 240px"
                    @change='changeVenuesSelect'
                    :disabled='isEdit'
                  >
                    <el-option
                      v-for="dict in venuesProgrammeList"
                      :key="dict.venuesProgrammeId"
                      :label="dict.programmeName"
                      :value="dict.venuesProgrammeId"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- 选择门票后展示详细信息 -->
          <el-col :span="24" v-if='form.venuesProgrammeId'>
            <el-row>
              <el-col :span="11">
          <el-form-item label="开始时间" prop="programmeStart">
            <el-date-picker clearable
              v-model="venuesProgrammeSelected.programmeStart"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择方案开始时间" disabled>
            </el-date-picker>
          </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="结束时间" prop="programmeEnd">
            <el-date-picker clearable
              v-model="venuesProgrammeSelected.programmeEnd"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择方案结束时间" disabled>
            </el-date-picker>
          </el-form-item>
          </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-divider content-position="left" v-if='form.venuesProgrammeId'>方案时间段信息</el-divider>
        <el-row :gutter="10" class="mb8" v-if='form.venuesProgrammeId'>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTicVenuesProgrammePeriod">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTicVenuesProgrammePeriod">删除</el-button>
          </el-col>
        </el-row>
        <el-table  v-if='form.venuesProgrammeId' :data="venuesProgrammeSelected.ticVenuesProgrammePeriodList" :row-class-name="rowTicVenuesProgrammePeriodIndex" @selection-change="handleTicVenuesProgrammePeriodSelectionChange" ref="ticVenuesProgrammePeriod">
          <el-table-column type="selection" width="50" align="center" />
          <!-- <el-table-column label="序号" align="center" prop="index" width="50"/> -->
          <el-table-column label="开始时间" prop="periodTimeStart" >
            <template slot-scope="scope">
              <el-time-picker clearable
                style="width:135px"
                v-model="scope.row.periodTimeStart"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                :picker-options="{selectableRange:'00:00:00-23:59:59'}"
                placeholder="请选择开始时间">
              </el-time-picker>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" prop="periodTimeEnd" >
            <template slot-scope="scope">
              <el-time-picker clearable
                style="width:135px"
                v-model="scope.row.periodTimeEnd"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                :picker-options="{selectableRange:  `${scope.row.periodTimeStart}-23:59:59`}"
                placeholder="请选择结束时间">
              </el-time-picker>
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="periodPrice" width="210">
            <template slot-scope="scope">
              <el-input-number  v-model="scope.row.periodPrice" placeholder="请输入价格"  :min="0" :precision="2" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="总库存" prop="periodStockCount" width="210">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.periodStockCount" placeholder="请输入库存" :min="0"  controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="剩余库存" prop="periodStockResidue" width="210">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.periodStockResidue" placeholder="请输入库存" :min="0"  controls-position="right" disabled/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVenues, getVenues, addVenues, updateVenues, getListTicOherBase,getListScenic,getVenuesList} from "@/api/ticket/venuesstock";

export default {
  name: "Venues",
  dicts: ['ticket_venues_status', 'sys_user_auth'],
  data() {
    return {
      // 场馆下拉列表
      dictScenicList:[],
      // 选中场馆
      dictScenicListSelected:'',
      // 方案下拉列表
      venuesProgrammeList:[],
      // 选中方案
      venuesProgrammeSelected:'',
      // 判断是否编辑新增
      isEdit:false,
      // 门票下拉列表
      dictStockList:[],
      // 选中门票
      dictStockListSelected:'',
      // 方案信息子表选中数据
      checkedTicVenuesProgrammePeriod: [],
      scenicStockDate:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场馆门票表格数据
      venuesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        venuesName: null,
        venuesPhone: null,
        venuesType: null,
        stockDateEnd: null,
        stockDateStart: null,
        ticOtherBaseId: null,
        scenicAuth: null,
        venuesProgrammeId: null,
        ticOtherBaseId: null
      },
      startPickerOptions: {
        disabledDate: (time) => {
          let endTime = this.form.endTime
          if (endTime) {
            return time.getTime() > new Date(endTime).getTime()
          }
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          let startTime = this.form.startTime
          if (startTime) {
            return time.getTime() < new Date(startTime).getTime()
          }
        }
      },
      startPickerOptionsQuery: {
        disabledDate: (time) => {
          let endTime = this.queryParams.stockDateEnd
          if (endTime) {
            return time.getTime() > new Date(endTime).getTime()
          }
        }
      },
      endPickerOptionsQuery: {
        disabledDate: (time) => {
          let startTime = this.queryParams.stockDateStart
          if (startTime) {
            return time.getTime() < new Date(startTime).getTime()
          }
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        venuesPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        endTime:[
          { required: true, trigger: "blur", message: "请输入门票日期" },
        ],
        venuesId:[
          { required: true, message: "请选择门票",trigger: "change",},
        ],
        venuesProgrammeId:[
          { required: true, message: "请选择方案",trigger: "change",},
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTicOherBase();
    this.getStockSelectList();
  },
  methods: {
    // 获取场馆信息
    getTicOherBase(){
      getListTicOherBase().then(res=>{
        this.dictScenicList=res.data
      })
    },
    // 选择场馆
    changeScenicSelect(selected){
      console.log('选择场馆',this.dictScenicList,selected)
      this.form.ticOtherBaseId=selected
      this.dictScenicList.map(item=>{
        if(item.ticOtherId==selected){
          this.dictScenicListSelected=item
        }
      })

    },
    // 获取门票信息
    getStockSelectList(){
      getListScenic().then(res=>{
        this.dictStockList=res.data
      })
    },
    // 选择门票
    changeStockSelect(selected){
      console.log(this.dictStockList,selected)
      if(selected){
        this.dictStockList.map(item=>{
          if(item.venuesId==selected){
            this.dictStockListSelected=item
            // 自动带出景点信息
            this.changeScenicSelect(item.ticOtherBaseId)
            // 选择门票后带出方案下拉列表
            this.getVenuesList(item.ticOtherBaseId)
          }
        })
      }else{
        this.changeScenicSelect('')
        this.changeVenuesSelect('')
      }
    },
    // 获取方案下拉
    getVenuesList(ticOtherBaseId){
      return new Promise((resolve, reject) => {
        getVenuesList(ticOtherBaseId).then(res=>{
          this.venuesProgrammeList=res.data
          resolve(res)
        })
      }).catch(error => {
          reject(error)
      })
    },
    changeVenuesSelect(selected){
      return new Promise((resolve, reject) => {
        this.form.venuesProgrammeId=selected
        console.log('选择方案',this.venuesProgrammeList,selected)
        if(selected){
          this.venuesProgrammeList.map(item=>{
            if(item.venuesProgrammeId==selected){
              this.venuesProgrammeSelected=item
              console.log(this.venuesProgrammeSelected)
            }
          })
        }else{

        }
        resolve()
      }).catch(error => {
          reject(error)
      })
    },
    /** 方案时间段添加按钮操作 */
    handleAddTicVenuesProgrammePeriod() {
      let obj = {};
      obj.isDel = "";
      obj.ticOtherBaseId = "";
      obj.periodTimeStart = "";
      obj.periodTimeEnd = "";
      obj.periodPrice = "";
      obj.periodStockCount = "";
      this.venuesProgrammeSelected.ticVenuesProgrammePeriodList.push(obj);
    },
    /** 方案时间段序号 */
    rowTicVenuesProgrammePeriodIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 方案时间段删除按钮操作 */
    handleDeleteTicVenuesProgrammePeriod() {
      if (this.checkedTicVenuesProgrammePeriod.length == 0) {
        this.$modal.msgError("请先选择要删除的方案时间段数据");
      } else {
        const ticVenuesProgrammePeriodList = this.venuesProgrammeSelected.ticVenuesProgrammePeriodList;
        const checkedTicVenuesProgrammePeriod = this.checkedTicVenuesProgrammePeriod;
        this.venuesProgrammeSelected.ticVenuesProgrammePeriodList = ticVenuesProgrammePeriodList.filter(function(item) {
          return checkedTicVenuesProgrammePeriod.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTicVenuesProgrammePeriodSelectionChange(selection) {
      this.checkedTicVenuesProgrammePeriod = selection.map(item => item.index)
    },
    /** 查询场馆门票列表 */
    getList() {
      this.loading = true;
      listVenues(this.queryParams).then(response => {
        this.venuesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        venuesId: null,
        limitPurchaseNum: null,
        venuesStatus: null,
        createBy: null,
        createTime: null,
        startTime: null,
        endTime: null,
        ticOtherBaseId: null,
        scenicAuth: null,
        venuesProgrammeId: null,
        ticOtherBaseId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ticVenuesConfigId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场馆门票";
      this.isEdit=false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit=true
      const ticVenuesConfigId = row.ticVenuesConfigId || this.ids
      getVenues(ticVenuesConfigId).then(async response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改场馆门票";
        // 默认带出门票信息
        this.changeStockSelect(response.data.venuesId)
        // 根据场馆id 自动获取匹配的方案列表
        await this.getVenuesList(response.data.ticOtherBaseId)
        // 根据方案id，带出已选择的方案
        await this.changeVenuesSelect(response.data.venuesProgrammeId)
        // 默认带出门票信息-门票日期
        this.scenicStockDate=response.data.venuesDate
        // 方案时间段
        this.venuesProgrammeSelected.ticVenuesProgrammePeriodList=response.data.venuesPeriodList
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.venuesPeriodList=this.venuesProgrammeSelected.ticVenuesProgrammePeriodList
      console.log(this.form)
      this.form.sysStoresId=this.dictScenicListSelected.sysStoresId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.venuesPeriodList.length<=0){
              this.$modal.msgError("请添加方案时间段信息后保存");
              return
          }
          for(var i=0;i<this.form.venuesPeriodList.length;i++){
            let item=this.form.venuesPeriodList[i]
            if(!item.periodTimeStart || !item.periodTimeEnd){
              this.$modal.msgError("请填写完整的方案时间段信息后保存");
              return
            }
          }
          if (this.form.ticVenuesConfigId != null) {
            updateVenues(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVenues(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ticket/venues/export', {
        ...this.queryParams
      }, `venues_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
